﻿using Microsoft.Extensions.Caching.Memory;
using OAS.Application.AttendanceApp.Services;
using OAS.Application.System.Dtos;
using OAS.Core;
using OfficeOpenXml.Style;
using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Furion.FriendlyException;
using OAS.Application.AttendanceApp.Enums;

namespace OAS.Application.AttendanceApp
{
    public class AttendanceController : IDynamicApiController
    {
        private readonly ISqlSugarClient db;
        private readonly IAttendanceService _attendanceService;
        public AttendanceController(IAttendanceService attendanceService, ISqlSugarClient db)
        {
            this.db = db;
            _attendanceService = attendanceService;
        }
        //考勤
        public async Task<List<Attendance>> GetAllAttendance()
        {
            return await _attendanceService.GetAllAttendance();
        }
        [HttpPost]
        public async Task<object> GetAttendanceList(DtoQuery dto)
        {
            return await _attendanceService.GetAttendanceList(dto);
        }
        public async Task AddAttendance(Attendance attendance)
        {
            await _attendanceService.AddAttendance(attendance);
        }
        public async Task UpdateAttendance(Attendance attendance)
        {
            await _attendanceService.UpdateAttendance(attendance);
        }
        public async Task DeleteAttendance([FromBody] string[] ids)
        {
            await _attendanceService.DeleteAttendance(ids);
        }
        public async Task UserAttendance()
        {
            await _attendanceService.UserAttendance();
        }
        [HttpPost, NonUnify]
        public async Task<IActionResult> ExportAttendance(DtoQuery dto)
        {
            var list = await _attendanceService.GetAttendanceExport(dto);
            DataTable dt = EPPlusHandler.ListToDataTable(list);
            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
            ExcelPackage package = new ExcelPackage();
            //创建sheet1
            ExcelWorksheet sheet = package.Workbook.Worksheets.Add("考勤记录");
            int a = 1;
            foreach (DataColumn dc in dt.Columns)
            {
                string colName = dc.ColumnName;
                string cnName;
                switch (colName)
                {
                    case "UserName":
                        cnName = "工号";
                        break;
                    case "UserTrueName":
                        cnName = "考勤人";
                        break;
                    case "RecordDate":
                        cnName = "考勤日期";
                        break;
                    case "ClockInTime":
                        cnName = "上班时间";
                        break;
                    case "ClockOutTime":
                        cnName = "下班时间";
                        break;
                    case "StatusName":
                        cnName = "状态";
                        break;
                    default:
                        continue;
                }
                sheet.Cells[1, a].Value = cnName;
                ////设置行高
                sheet.Row(1).Height = 19.5;
                ////设置基本样式
                sheet.Cells[1, a].Style.Font.Name = "宋体";
                sheet.Cells[1, a].Style.Font.Size = 11F;
                sheet.Cells[1, a].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                sheet.Cells[1, a].Style.VerticalAlignment = ExcelVerticalAlignment.Center;
                //设置单元格边框
                //sheet.Cells[1, a].Style.Border.BorderAround(ExcelBorderStyle.Thin, System.Drawing.Color.Black);
                ////设置区域背景颜色（设置背景颜色之前一定要设置PatternType）
                //sheet.Cells["A1:E1"].Style.Fill.PatternType = ExcelFillStyle.Solid;
                //sheet.Cells["A1:E1"].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.FromArgb(232, 232, 232));
                a++;
                int b = 2;
                foreach (DataRow dr in dt.Rows)
                {
                    sheet.Cells[b, a - 1].Value = dr[colName];
                    b++;
                }
            }
            //保存
            package.Save();
            Stream stream = package.Stream;
            stream.Seek(0, SeekOrigin.Begin);
            return new FileStreamResult(stream, "application/octet-stream")
            {
                FileDownloadName = "考勤记录.xlsx"
                // 配置文件下载显示名
            };
        }
        [HttpPost, NonUnify]
        public Task<IActionResult> DownloadTemplateAttendance()
        {
            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
            ExcelPackage package = new();
            //创建sheet1
            ExcelWorksheet sheet = package.Workbook.Worksheets.Add("考勤记录");
            int a = 1;
            List<string> header = new() { "工号", "考勤日期", "上班时间", "下班时间", "状态" };
            foreach (string cnName in header)
            {
                sheet.Cells[1, a].Value = cnName;
                ////设置行高
                sheet.Row(1).Height = 19.5;
                ////设置基本样式
                sheet.Cells[1, a].Style.Font.Name = "宋体";
                sheet.Cells[1, a].Style.Font.Size = 11F;
                sheet.Cells[1, a].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                sheet.Cells[1, a].Style.VerticalAlignment = ExcelVerticalAlignment.Center;
                //设置单元格边框
                //sheet.Cells[1, a].Style.Border.BorderAround(ExcelBorderStyle.Thin, System.Drawing.Color.Black);
                ////设置区域背景颜色（设置背景颜色之前一定要设置PatternType）
                //sheet.Cells["A1:E1"].Style.Fill.PatternType = ExcelFillStyle.Solid;
                //sheet.Cells["A1:E1"].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.FromArgb(232, 232, 232));
                a++;
            }
            //保存
            package.Save();
            Stream stream = package.Stream;
            stream.Seek(0, SeekOrigin.Begin);
            return Task.FromResult<IActionResult>(new FileStreamResult(stream, "application/octet-stream")
            {
                FileDownloadName = "考勤记录导入模板.xlsx"
            });
        }
        /// <summary>
        /// 读取Excel表格内容
        /// </summary>
        public async Task<string> ImportAttendance(IFormFile file)
        {
            var savePath = Path.Combine(App.HostEnvironment.ContentRootPath, "uploads");
            if (!Directory.Exists(savePath)) Directory.CreateDirectory(savePath);
            var fileName = Guid.NewGuid().ToString("N") + Path.GetExtension(file.FileName);
            var filePath = Path.Combine(savePath, fileName);
            // 保存到指定路径
            FileStream fs = File.Create(filePath);
            await file.CopyToAsync(fs);
            ExcelPackage package = new(fs);
            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
            ExcelWorksheet sheet = package.Workbook.Worksheets[0];
            int n = sheet.Dimension.End.Row;
            List<Attendance> list = new();
            for (int i = 2; i <= n; i++)
            {
                Attendance attendance = new()
                {
                    UserName = sheet.GetValue(i, 1).ToString(),
                    RecordDate = Convert.ToDateTime(sheet.GetValue(i, 2).ToString()),
                    ClockInTime = Convert.ToDateTime(sheet.GetValue(i, 3)?.ToString()),
                    ClockOutTime = Convert.ToDateTime(sheet.GetValue(i, 4)?.ToString()),
                    Status = (int)Enum.Parse(typeof(AttendanceStatus), sheet.GetValue(i, 5).ToString()),
                };
                list.Add(attendance);
            }
            fs.Close();
            var importCount = await db.Insertable(list).ExecuteCommandAsync();
            return $"成功导入{importCount}条记录数";
        }
    }
}
